package cn.cnlee.arch.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.tqzhang.stateview.core.LoadManager;
import com.tqzhang.stateview.stateview.BaseStateControl;

import org.jetbrains.annotations.NotNull;

/**
 * Fragment的基类
 */
public abstract class BaseFragment extends Fragment {
    protected View rootView;//根视图

    protected FragmentActivity activity;//Fragment当前所属的Activity

    protected LoadManager loadManager;//StateView视图管理器

    protected boolean mIsFirstVisible = true;//是否首次可见（即UI初始化）
    protected boolean mIsVisible = false;//界面是否可见

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
        rootView = inflater.inflate(getLayoutResId(), null, false);
        View contentLayout = rootView.findViewById(getContentResId());
        if (contentLayout != null) {
            loadManager = new LoadManager.Builder()
                    .setViewParams(contentLayout)
                    .setListener(new BaseStateControl.OnRefreshListener() {
                        @Override
                        public void onRefresh(View v) {
                            onStateRefresh();
                        }
                    })
                    .build();
        }
        initView(state);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        mIsVisible = true;
    }

    @Override
    public void onPause() {
        super.onPause();
        mIsVisible = false;
    }

    /**
     * @return 布局Layout的ResourceID
     */
    public abstract int getLayoutResId();

    /**
     * 初始化views
     *
     * @param state
     */
    public abstract void initView(Bundle state);

    /**
     * @return 需要配置stateView的视图
     */
    protected int getContentResId() {
        return -1;
    }

    /**
     * stateView视图的状态刷新事件
     */
    protected abstract void onStateRefresh();

    /**
     * 数据懒加载
     */
    protected void lazyLoad() {
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        this.activity = null;
    }

    @Override
    public void onAttach(@NotNull Context context) {
        super.onAttach(context);
        this.activity = (FragmentActivity) context;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        this.activity = null;
    }

    @SuppressWarnings("unchecked")
    protected <T extends View> T getViewById(int id) {
        return (T) rootView.findViewById(id);
    }


}
